package com.sxg.common;

import com.alibaba.fastjson2.JSON;
import com.google.code.kaptcha.Producer;
import com.sxg.annotation.Anonymous;
import com.sxg.config.RabbitMqConfig;
import com.sxg.constant.CacheConstants;
import com.sxg.constant.Constants;
import com.sxg.entity.SxgDouAreaEntity;
import com.sxg.entity.SxgOrderEntity;
import com.sxg.redis.RedisCache;
import com.sxg.service.SxgOrderService;
import com.sxg.service.impl.SxgDouAreaServiceImpl;
import com.sxg.utils.Base64;
import com.sxg.utils.IdUtils;
import com.sxg.utils.MailTemplateUtils;
import com.sxg.utils.SecurityUtils;
import com.sxg.utils.code.AjaxResult;
import com.sxg.utils.code.Result;
import com.sxg.vo.CloseOrder;
import com.sxg.vo.req.EmailReqVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
@Slf4j
public class CaptchaController {

    @Value("${sxg.captchaType}")
    private String captchaType;
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private AmqpTemplate amqpTemplate;

    @Resource
    private SxgOrderService sxgOrderService;

    @GetMapping("test")
    @Anonymous
    public void test(@RequestParam String time, @RequestParam String orderId) {
        SxgOrderEntity byId = sxgOrderService.getById(orderId);
        amqpTemplate.convertAndSend(RabbitMqConfig.ORDER_DELAY_EXCHANGE, RabbitMqConfig.ORDER_DELAY_KEY, byId, message -> {
            message.getMessageProperties().setHeader("x-delay", time);
            return message;
        });
    }


    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Result getCode() throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return Result.ok(map);
    }

    @PostMapping("/email")
    @Anonymous
    public AjaxResult sendEmailCaptcha(@RequestBody EmailReqVo vo) {
        String qq = null;
        try {
            qq = vo.getEmail().substring(0, vo.getEmail().indexOf("@"));
        } catch (Exception e) {
            return AjaxResult.error("邮箱格式错误");
        }
        String key = CacheConstants.MAIL_CODE_KEY + qq;
        Object object = redisCache.getCacheObject(key);
        if (object != null) {
            return AjaxResult.error("验证码发送太频繁，请稍后再试");
        }
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //获取验证码
            String code = MailTemplateUtils.generatedcode(5);
            //创建简单邮件消息
            log.error("发送邮件开始，内容：{}，收件人：{}", code, vo.getEmail());
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发的
            helper.setFrom(from);
            //谁要接收
            helper.setTo(vo.getEmail());
            //邮件标题
            helper.setSubject("书香阁验证码");
            //邮件内容
            helper.setText(MailTemplateUtils.buildContent(code), true);
            javaMailSender.send(message);
            log.error("发送邮件结束");
            //成功后存入redis
            redisCache.setCacheObject(key, code, 5, TimeUnit.MINUTES);
        } catch (MessagingException e) {
            return AjaxResult.success("邮件发送失败");
        }
        return AjaxResult.success("邮件发送成功");
    }


}
